package com.cd.socialMarketing.service;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service("mailService")
public class MailService {

	public void enviarMail(String from, String name, String subject, String text) throws MessagingException {

		String mailHost = SpringPropertiesUtil.getProperty("app.mail.host");
		String mailUserName = SpringPropertiesUtil.getProperty("app.mail.username");
		String mailPassword = SpringPropertiesUtil.getProperty("app.mail.password");
		String mailBounce = SpringPropertiesUtil.getProperty("app.mail.bounce");
		
    	try{
    		Properties props = new Properties();

    		props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.host", mailHost);
			
			final String username = mailUserName;
			final String password = mailPassword;
    		
    		props.put("mail.smtp.port", "25");
    		props.put("mail.smtp.from", mailBounce);
    		
    		Session session = Session.getInstance(props,
			  new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			  });
    		
    		MimeMessage message = new MimeMessage(session);

    		MimeMessageHelper helper = new MimeMessageHelper(message,true,"iso-8859-1");
	    	helper.setFrom(name+" <"+from+">");
	    	helper.setTo(mailBounce);
			helper.setSubject(subject);
			helper.setText(text,true);
	
			Transport.send(message);
    	}catch (Exception e) {
			e.printStackTrace();
		}
    }
}